<script setup lang="ts">
import { ref, watch } from 'vue'
import { getUser, addUser, updateUser, deleteUser } from '@st/modules/permission/api/users'
import RolePicker from '@st/modules/permission/components/role-picker/RolePicker.vue'
import FormUser from '@st/modules/permission/components/form-user/FormUser.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
// import { EditPen, Delete } from '@element-plus/icons-vue'
import { throttle } from '@/utils/system'

const fullscreenLoading = ref(false)

const searchForm = ref<any>({})

const roleId = ref<string>('')

const tableRefreshKey = ref(`${new Date().getTime()}`)

const conditionMethod = () => {
  const cond: any = {}
  Object.keys(searchForm.value).map((key) => {
    if (searchForm.value[key] || searchForm.value[key] === 0) {
      if (key === 'rangeDate') {
        if (searchForm.value[key]) {
          cond['startTime'] = searchForm.value[key][0]
          cond['endTime'] = searchForm.value[key][1]
        }
      } else {
        cond[key] = searchForm.value[key]
      }
    }
  })
  cond['roleIdList'] = roleId.value ? [roleId.value] : []
  return cond
}

const handleSearch = () => {
  tableRefreshKey.value = `${new Date().getTime()}`
}

const handleResetSearch = () => {
  searchForm.value = {}
  tableRefreshKey.value = `${new Date().getTime()}`
}

watch(roleId, () => {
  tableRefreshKey.value = `${new Date().getTime()}`
})

// 改变用户状态
const handleChangeStatus = (userId: any, status: any) => {
  console.log(userId, status)
  updateUser({ userId, useStatus: status })
    .then(() => {
      ElMessage({
        message: '修改成功!',
        type: 'success'
      })
    })
    .finally(() => {
      tableRefreshKey.value = `${new Date().getTime()}`
    })
}

// 删除
const handleDelete = (row: any) => {
  let { userId } = row
  ElMessageBox.confirm('确定删除用户?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    autofocus: false
  }).then(() => {
    deleteUser({ userId })
      .then(() => {
        ElMessage({
          message: '删除成功!',
          type: 'success'
        })
      })
      .finally(() => {
        tableRefreshKey.value = `${new Date().getTime()}`
      })
  })
}

// 添加编辑
const dialogVisible = ref(false)

const addEditData = ref<any>({})

const addEditStatus = ref('add')

const formUserRef = ref()

const handleAdd = () => {
  addEditStatus.value = 'add'
  addEditData.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  addEditStatus.value = 'edit'
  const { userId, phone, userName, sysRoleEntityList } = row
  addEditData.value = {
    userId: userId,
    phone: phone,
    userName: userName,
    roleIdList: sysRoleEntityList.map((item: any) => item.roleId)
  }
  dialogVisible.value = true
}

const handleDialogClose = () => {
  dialogVisible.value = false
}

const handleDialogSubmit = throttle(() => {
  formUserRef.value.submitForm().then((data: any) => {
    if (data) {
      fullscreenLoading.value = true
      const { userId, userName, phone, password, roleIdList } = data
      if (userId) {
        updateUser({ userId, userName, phone, roleIdList })
          .then(() => {
            ElMessage({
              message: '更新成功!',
              type: 'success'
            })
            dialogVisible.value = false
            tableRefreshKey.value = `${new Date().getTime()}`
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      } else {
        addUser({ userName, phone, password, roleIdList })
          .then(() => {
            ElMessage({
              message: '新增成功!',
              type: 'success'
            })
            dialogVisible.value = false
            tableRefreshKey.value = `${new Date().getTime()}`
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      }
    }
  })
})
</script>

<template>
  <BasePage v-loading.fullscreen="fullscreenLoading" searchbar>
    <template #title>用户管理</template>
    <template #toolbar>
      <el-button type="primary" @click="handleAdd">
        <template #icon>
          <SvgIcon icon="plain-add"></SvgIcon>
        </template>
        新增
      </el-button>
    </template>
    <template #searchbar>
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键字：">
          <el-input v-model="searchForm.userName" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="info" text bg @click="handleResetSearch">
            <template #icon>
              <SvgIcon icon="plain-reset"></SvgIcon>
            </template>
            重置
          </el-button>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <SvgIcon icon="plain-search"></SvgIcon>
            </template>
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <div class="page-content-container">
      <div class="left">
        <RolePicker v-model="roleId"></RolePicker>
      </div>
      <div class="right">
        <BaseTable :init-table-method="getUser" :condition-method="conditionMethod" :refresh-key="tableRefreshKey">
          <el-table-column type="index" label="编号" align="center" header-align="center" width="80"></el-table-column>
          <el-table-column prop="userName" label="昵称" min-width="100" show-overflow-tooltip></el-table-column>
          <el-table-column prop="phone" label="手机号/账号" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="roleName" label="角色" min-width="160">
            <template #default="scope">
              <el-tag v-for="(item, index) in scope.row.sysRoleEntityList" :key="index" type="success" class="role-tag">{{ item.roleName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="160">
            <template #default="scope">
              <el-switch
                v-model="scope.row.useStatus"
                :active-value="1"
                :inactive-value="0"
                @change="
                  (val: any) => {
                    handleChangeStatus(scope.row.userId, val)
                  }
                "
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
              <!-- <div class="icon-text-box">
                <div class="icon-text info" @click.stop="handleEdit(scope.row)">
                  <el-icon class="icon"><EditPen /></el-icon>
                  <div class="text">编辑</div>
                </div>
                <div class="icon-text delete" @click.stop="handleDelete(scope.row)">
                  <el-icon class="icon"><Delete /></el-icon>
                  <div class="text">删除</div>
                </div>
              </div> -->
            </template>
          </el-table-column>
        </BaseTable>
      </div>
    </div>
  </BasePage>
  <BaseDialog v-model="dialogVisible">
    <template #title>{{ addEditStatus === 'add' ? '新增' : '编辑' }}</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogClose">取消</el-button>
      <el-button type="primary" @click="handleDialogSubmit">保存</el-button>
    </template>
    <FormUser ref="formUserRef" :data="addEditData" :status="addEditStatus"></FormUser>
  </BaseDialog>
</template>

<style lang="scss" scoped>
.page-content-container {
  @include rect(100%, 100%);
  @include flex(row, space-between, flex-start);
  .left {
    @include rect(220px, 100%);
    box-sizing: border-box;
    padding-bottom: 24px;
  }
  .right {
    @include rect(calc(100% - 240px), 100%);
    :deep(.role-tag) {
      margin-right: 10px;
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .icon-text-box {
      display: flex;
      justify-content: center;
      align-items: center;

      .icon-text {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 24px;
        cursor: pointer;
        .icon {
          margin-right: 5px;
          font-size: 16px;
        }
        .text {
          width: 2em;
        }
        .text.add {
          min-width: 4em;
        }
      }
      .icon-text:last-child {
        margin-right: 0;
      }
      .icon-text.info {
        color: var(--theme-color);
      }
      .icon-text.delete {
        color: #f56c6c;
      }
    }
  }
}
</style>
